import { code } from '@/apis/codeApi'
import Request from './request'
import { API_URL } from '@/env.js'
import store from '@/store'

const shoproRequest = new Request()
export default function http (
  api,
  data = {},
  toastBefore = '', // 请求前加载提示
  toastAfter = true, // 请求后错误提示
) {
  // let api = getApiPath(url)
  /* 请求之前拦截器 */
  shoproRequest.interceptor.request((config, cancel) => {
    let token = uni.getStorageSync('token')
    let code = uni.getStorageSync('code')
    // uni.showLoading({
    //   title: '加载中...',
    //   icon: 'none',
    // })
    let login = api.login === undefined ? true : api.login
    if (api.auth && !token && login) {
      uni.hideLoading()
      uni.showToast({
        title: '未登录,请登录',
        icon: 'none',
        duration: 3000,
      })
      store.commit('userStore/setLogin', false)
      store.commit('userStore/setUserInfo', {})
      setTimeout(() => {
        uni.navigateTo({
          url: '/pages/login/login',
        })
      },2000)

      throw `暂未登录,已阻止此次API请求: '${api.url}'`
    }
    token &&
    shoproRequest.setConfig((config) => {
      config.header.Authorization = 'Bearer ' + token
    })
    code &&
    shoproRequest.setConfig((config) => {
      config.header.xcode = code
    })
    code &&
    shoproRequest.setConfig((config) => {
      config.header['X-Requested-With'] = 'XMLHttpRequest'
    })
    if (toastBefore !== '') {
      uni.showLoading({
        title: toastBefore,
        mask: true,
      })
    }
    return config
  })

  /* 请求之后拦截器 */
  shoproRequest.interceptor.response((response) => {
    uni.hideLoading()
    if (response.code === 0) {
      if (toastAfter) {
        uni.showToast({
          title: response.message || '请求出错,稍后重试',
          icon: 'none',
          duration: 3000,
          mask: true,
        })
      }
    }

    // token过期注销
    if (response.code === 401) {
      let app = getApp()
      uni.clearStorageSync()
      //当token过期时重新请求code放入缓存中
      code({
        app_id: app.globalData.appId,
        channel: 'wx_applet',
      }).then((res) => {
        uni.setStorageSync('code', res.data)
      })

      if (api.login || api.login == undefined) {
        uni.showToast({
          title: '未登录,请登录',
          icon: 'none',
          duration: 3000,
        })
        store.commit('userStore/setLogin', false)
        store.commit('userStore/setUserInfo', {})
        setTimeout(() => {
          uni.navigateTo({
            url: '/pages/login/login',
          })
        },2000)
        // setTimeout(() => {
        //   // store.commit('changeIndex', 4)
        //   store.commit('')
        //   uni.switchTab({
        //     url: `/pages/my/index`,
        //   })
        // }, 3000)
        throw `登录已过期或注销,已阻止此次API请求: '${api.url}'`
      }
    }
    return response
  })

  return shoproRequest.request({
    url: API_URL + api.url,
    data: api.data,
    method: api.method,
  })
}

// 组装接口路径
function getApiPath (url) {
  let apiArray = url.split('.')
  let api = apiList
  apiArray.forEach((v) => {
    api = api[v]
  })
  return api
}

export { shoproRequest }
